import React, { useState, useEffect } from "react";
import {
  StyleSheet,
  View,
  Text,
  TextInput,
  BackHandler,
  ScrollView,
} from "react-native";
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { SafeAreaView } from "react-native-safe-area-context";
import { getQuestionById } from "@/mocks/questions";
import { useUserStore } from "@/store/user-store";
import { SimulationResult, UserAnswer, Question } from "@/types/question";
import { useTheme } from "@/hooks/useTheme";
import Button from "@/components/Button";
import Timer from "@/components/Timer";

export default function SimulationQuestionScreen() {
  const router = useRouter();
  const { colors } = useTheme();
  const { questionIds, duration, current } = useLocalSearchParams<{
    questionIds: string;
    duration: string;
    current: string;
  }>();
  const [answer, setAnswer] = useState("");
  const [answers, setAnswers] = useState<UserAnswer[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const addSimulation = useUserStore((state) => state.addSimulation);
  const questionIdArray = questionIds.split(",");
  const currentIndex = parseInt(current, 10);
  const currentQuestionId = questionIdArray[currentIndex];
  const [currentQuestion, setCurrentQuestion] = useState<Question | null>(null);
  useEffect(() => {
    const loadQuestion = async () => {
      try {
        const question = await getQuestionById(currentQuestionId);
        setCurrentQuestion(question || null);
      } catch (error) {
        console.error('Error loading question:', error);
      }
    };
    loadQuestion();
  }, [currentQuestionId]);
  const isLastQuestion = currentIndex === questionIdArray.length - 1;
  useEffect(() => {
    // Prevent going back with hardware back button
    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      () => true
    );
    return () => backHandler.remove();
  }, []);
  const handleTimeUp = () => {
    handleNext();
  };
  const handleNext = () => {
    if (!currentQuestion) return;
    setIsSubmitting(true);
    // Save the current answer
    const userAnswer: UserAnswer = {
      questionId: currentQuestion.id,
      userAnswer: answer,
      score: 0, // Will be evaluated later
      timestamp: Date.now(),
    };
    setAnswers((prev) => [...prev, userAnswer]);
    // If this is the last question, go to results
    if (isLastQuestion) {
      const simulationResult: SimulationResult = {
        id: Date.now().toString(),
        date: Date.now(),
        questions: questionIdArray,
        answers: [...answers, userAnswer],
        totalScore: 0, // Will be calculated in results screen
        duration: parseInt(duration, 10),
      };
      addSimulation(simulationResult);
      router.replace({
        pathname: "/simulation/results",
        params: { simulationId: simulationResult.id },
      });
    } else {
      // Go to next question
      router.replace({
        pathname: "/simulation/question",
        params: {
          questionIds,
          duration,
          current: (currentIndex + 1).toString(),
        },
      });
    }
    setIsSubmitting(false);
    setAnswer("");
  };
  if (!currentQuestion) {
    return (
      <View style={[styles.container, { backgroundColor: colors.background }]}>
        <Text style={[styles.errorText, { color: colors.text }]}>未找到问题</Text>
      </View>
    );
  }
  return (
    <SafeAreaView style={[styles.container, { backgroundColor: colors.background }]} edges={["bottom"]}>
      <Stack.Screen
        options={{
          title: "面试模拟",
          headerStyle: {
            backgroundColor: colors.background,
          },
          headerTintColor: colors.text,
          headerBackVisible: false,
          headerRight: () => (
            <Timer
              duration={parseInt(duration, 10) / questionIdArray.length}
              onComplete={handleTimeUp}
            />
          ),
        }}
      />
      <ScrollView style={styles.content}>
        <View style={styles.progress}>
          <Text style={[styles.progressText, { color: colors.subtext }]}>
            问题 {currentIndex + 1} / {questionIdArray.length}
          </Text>
          <View style={[styles.progressBar, { backgroundColor: "rgba(255, 255, 255, 0.1)" }]}>
            <View
              style={[
                styles.progressFill,
                {
                  width: `${
                    ((currentIndex + 1) / questionIdArray.length) * 100
                  }%`,
                  backgroundColor: colors.primary,
                },
              ]}
            />
          </View>
        </View>
        <Text style={[styles.questionText, { color: colors.text }]}>{currentQuestion.question}</Text>
        <View style={styles.answerContainer}>
          <Text style={[styles.answerLabel, { color: colors.text }]}>你的回答:</Text>
          <TextInput
            style={[styles.answerInput, { 
              backgroundColor: colors.card, 
              color: colors.text, 
              borderColor: colors.border 
            }]}
            multiline
            placeholder="在此输入你的回答..."
            placeholderTextColor={colors.subtext}
            value={answer}
            onChangeText={setAnswer}
            autoFocus
          />
        </View>
      </ScrollView>
      <View style={styles.footer}>
        <Button
          title={isLastQuestion ? "完成面试" : "下一题"}
          onPress={handleNext}
          loading={isSubmitting}
          fullWidth
        />
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  content: {
    flex: 1,
    padding: 16,
  },
  progress: {
    marginBottom: 24,
  },
  progressText: {
    fontSize: 14,
    marginBottom: 8,
  },
  progressBar: {
    height: 6,
    borderRadius: 3,
    overflow: "hidden",
  },
  progressFill: {
    height: "100%",
    borderRadius: 3,
  },
  questionText: {
    fontSize: 18,
    fontWeight: "600",
    marginBottom: 24,
    lineHeight: 26,
  },
  answerContainer: {
    marginBottom: 24,
  },
  answerLabel: {
    fontSize: 16,
    fontWeight: "600",
    marginBottom: 8,
  },
  answerInput: {
    borderRadius: 8,
    padding: 16,
    minHeight: 200,
    fontSize: 16,
    textAlignVertical: "top",
    borderWidth: 1,
  },
  footer: {
    padding: 16,
  },
  errorText: {
    fontSize: 18,
    textAlign: "center",
    marginTop: 24,
  },
});
